// 用户信息相关操作
/*
 * @Author: Wangtao
 * @Date: 2022-08-22 22:31:54
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-22 15:33:41
 */
import { defineStore } from 'pinia'

import { getPlatformInfo } from '@/common/apis/user'

import { login, getLoginInfo, getLoginPre } from '@/common/apis/user'
import { PermissionModule } from '@/common/store/modules/permission'

import ls from '@/common/utils/localStore'
import mcCache from '@/common/utils/mc-get-cache'

import { Base64 } from 'js-base64'
import md5 from 'js-md5'
import { JSEncrypt } from 'jsencrypt'

import ROUTER from '@app/base/router'

export const userModule = defineStore('user', {
  state: () => {
    return {
      agent: {
        _id: '',
        accountId: '',
        icon: '',
        agentNumber: '',
        agentName: '',
        pinyin: '',
        mobile: '',
        email: '',
        password: '',
        salt: '',
        status: '',
        createTime: '',
        createAgent: '',
        updateTime: '',
        updateAgent: '',
        limits: ['test'],
        functions: [],
        agentCallConfig: { restTime: 30 }
      },
      account: {
        _id: '',
        customerId: '',
        loginName: '',
        name: '',
        status: '',
        productId: '',
        createTime: '',
        updateTime: ''
      },
      timestamp: '',
      clientType: '',
      canCall: '',
      loginToken: '',
      wsToken: '',
      wsExtra: '',
      sessionId: '',
      accountId: '',
      loginState: false,
      loginName: '',
      password: '',
      pushServer: [],
      timedifference: 0
    }
  },
  actions: {
    async getPlatformInfo() {
      const currentUrl = window.location.href.split('/')[2]
      const platformInfo = await getPlatformInfo({ domain: currentUrl })
      console.log(platformInfo)
    },
    async handleLogin(loginInfo: { loginName: string; password: string; clientType?: number }) {
      if (this.loginState) {
        return
      }
      let { loginName } = loginInfo
      const { clientType } = loginInfo
      const { password } = loginInfo
      loginName = loginName.trim()
      const customParam: any = {}
      if (clientType) {
        customParam.clientType = clientType
      }
      const preInfo = await getLoginPre()
      if (preInfo.success) {
        // 获取密码加密公钥
        const PUBLIC_KEY = decodeURIComponent(Base64.decode(preInfo.data.pk))
        const encryptor = new JSEncrypt()
        encryptor.setPublicKey(PUBLIC_KEY)
        const md5Password = md5(password)
        const rsaPassword = encryptor.encrypt(md5Password)
        const { data, success } = await login({ loginName, password: rsaPassword, ...customParam }).catch(() => {
          this.backLogin()
        })
        if (success) {
          this.loginToken = data.loginToken
          this.loginToken = data.sessionId
          this.clientType = data.clientType
          await window.sessionStorage.setItem('loginToken', data.loginToken)
          await window.sessionStorage.setItem('sessionId', data.sessionId)
          await window.sessionStorage.setItem('clientType', data.clientType)
          await ls.setItem('accountId', data.accountId)
          await ls.setItem('switchInfo', Base64.encode(JSON.stringify({ loginName: loginName, password: password })))
          return data
        } else {
          this.backLogin()
        }
      } else {
        console.error('获取公钥失败')
        this.backLogin()
        return false
      }
    },
    async getLoginInfo() {
      try {
        const { data } = await getLoginInfo()
        this.agent = data.agent
        this.pushServer = data.pushServer
        this.timedifference = new Date().getTime() - new Date(data.timestamp).getTime()
        mcCache.$getCache('userCache', 'hasObj') // 员工
        mcCache.$getCache('groupCache') // 服务组
        this.loginState = true
      } catch (err) {
        console.log(err)
      }
    },
    async filterRole() {
      const setClientType = this.clientType
      const PERMISSIONMODULE = PermissionModule()
      PERMISSIONMODULE.setClientType(Number(setClientType))
    },
    async handleSwitchClientType(routerQuery?: any) {
      // 系统切换处理逻辑
      if (routerQuery && routerQuery.clientType && !this.loginState) {
        // 切换系统时取切换数据
        const switchInfoString: string = (await ls.getItem('switchInfo')) || ''
        if (switchInfoString) {
          const switchInfo = JSON.parse(Base64.decode(switchInfoString))
          this.loginName = switchInfo.loginName
          this.password = switchInfo.password
        }
        if (this.loginName && this.password) {
          await this.handleLogin({
            clientType: routerQuery.clientType,
            loginName: this.loginName,
            password: this.password
          })
        }
      }
    },
    async getLoginCache() {
      // 设置当前系统缓存 先获取内存数据 没有再获取缓存
      if (!this.loginToken) {
        const loginToken: string = window.sessionStorage.getItem('loginToken') || ''
        this.loginToken = loginToken
      }

      if (!this.sessionId) {
        const sessionId: string = window.sessionStorage.getItem('sessionId') || ''
        this.sessionId = sessionId
      }

      if (!this.clientType) {
        const clientType: string = window.sessionStorage.getItem('clientType') || ''
        this.clientType = clientType
      }

      if (!this.accountId) {
        const accountId: string = (await ls.getItem('accountId')) || ''
        this.accountId = accountId
      }
    },
    async resetLoginToken() {
      await window.sessionStorage.removeItem('loginToken')
      await window.sessionStorage.removeItem('sessionId')
      await window.sessionStorage.removeItem('clientType')
      await ls.removeItem('accountId')
      await ls.removeItem('switchInfo')
      this.loginToken = ''
      this.sessionId = ''
      this.clientType = ''
      this.accountId = ''
      this.loginName = ''
      this.password = ''
    },
    async rememberLogininfo(info: any, type: string) {
      await ls.setItem(type, Base64.encode(info))
    },
    async forgetLoginInfo() {
      await ls.removeItem('loginInfo')
    },
    async getRememberInfo(type: string) {
      const loginInfo: any = await ls.getItem(type)
      if (loginInfo) {
        return JSON.parse(Base64.decode(loginInfo))
      }
    },
    switchClientType(clientType: number) {
      // if (this.loginName && this.password) {
      //   await this.handleLogin({ clientType: clientType, loginName: this.loginName, password: this.password })
      //   const PERMISSIONMODULE = PermissionModule()
      //   PERMISSIONMODULE.removeRoutes()
      //   await PERMISSIONMODULE.updateFilterState(false)
      //   return true
      // } else {
      //   return false
      // }
      // 切换系统改为跳转系统
      // const ROUTER = useRouter()
      // const routeUrl: any = ROUTER.resolve({
      //   path: '/app'
      // })
      // window.open(routeUrl.href, `-agent`)
    },
    setUserInfo(data: any) {
      // 设置全局的用户头像
      this.agent = data
    },
    async backLogin() {
      await this.resetLoginToken()
      ROUTER.push({
        path: '/login'
      })
    }
  }
})
